package com.mccken.practice.top100.Top_1$20.Top_27;

import com.mccken.practice.top100.ListNode;
import com.mccken.practice.top100.ListNodeUtil;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2024-02-14 22:19
 **/
public class RemoveNthFromEnd_19 {
	public ListNode removeNthFromEnd(ListNode head, int n) {
		ListNode pre = new ListNode(0);
		pre.next = head;

		ListNode slow = head;
		ListNode fast = head;

		for (int i = 0; i < n; i++) {
			fast = fast.next;
		}

		while (fast != null && fast.next != null) {
			slow = slow.next;
			fast = fast.next;
		}
		if (slow == null || slow.next == null) {
			return null;
		}

		// 细节点：搞清楚，到底需要删除的是 slow 还是 slow.next，如果
		if (fast == null) { // 删除 slow
			pre.next = slow.next;
			slow.next = null;
		} else {
			ListNode temp = slow.next;
			slow.next = slow.next.next;
			temp.next = null;
		}

		return pre.next;
	}

	/*
	base case1： 当n=1时，直接返回head.next
	
	
	 */
	public static void main(String[] args) {
		RemoveNthFromEnd_19 r = new RemoveNthFromEnd_19();
//		ListNode listNode = ListNodeUtil.buildListNode(new int[]{1, 2});
//		ListNode listNode1 = r.removeNthFromEnd(listNode, 1);
//		ListNode listNode1 = r.removeNthFromEnd(listNode, 2);
		ListNode listNode = ListNodeUtil.buildListNode(new int[]{1, 2, 3, 4, 5});
		ListNode listNode1 = r.removeNthFromEnd(listNode, 2);
		ListNodeUtil.printListNode(listNode1);
	}

}
